package com.chen.palmar.project.set;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.SelectPickerDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.SquareImageView;
import com.chen.palmar.entity.ApplyStoreRequest;
import com.chen.palmar.entity.NewListEntity;
import com.chen.palmar.entity.StoreDetailEntity;
import com.primb.androidlibs.net.converter.RxSchedulerUtils;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.primb.androidlibs.utils.FileUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import io.valuesfeng.picker.ImageSelectActivity;
import io.valuesfeng.picker.Picker;
import io.valuesfeng.picker.engine.GlideEngine;
import io.valuesfeng.picker.engine.PicassoEngine;
import rx.Subscription;

/**
 * @author Chen
 * @date 2018/1/10
 * 功能描述：
 */

public class ApplyStoreActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.rv_store_img)
    RecyclerView rvStoreImg;
    @Bind(R.id.tv_store_way)
    TextView tvStoreWay;
    @Bind(R.id.tv_store_out)
    TextView tvStoreOut;
    @Bind(R.id.tv_store_qz)
    TextView tvStoreQz;
    @Bind(R.id.et_store_date)
    EditText etStoreDate;
    @Bind(R.id.et_store_barcodes)
    EditText etStoreBarcodes;
    @Bind(R.id.et_store_brand)
    EditText etStoreBrand;
    @Bind(R.id.et_store_number)
    EditText etStoreNumber;
    @Bind(R.id.et_store_code)
    EditText etStoreCode;
    @Bind(R.id.et_store_name)
    EditText etStoreName;
    @Bind(R.id.et_store_price)
    EditText etStorePrice;
    @Bind(R.id.btn_apply_info)
    Button btnApplyInfo;
    private ArrayList<String> listTag = new ArrayList<>();
    private List<String> imgList = new ArrayList<>();
    private static final int REQUEST_CODE_IMG = 3;
    BaseQuickAdapter<String, BaseViewHolder> adapterImg;
    private ApplyStoreRequest request;
    private NewListEntity.DataBean info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        titleBar.setText("商品管理");
        toolBar.setNavigationOnClickListener(v -> ApplyStoreActivity.this.finish());

        info = ((NewListEntity.DataBean) getIntent().getSerializableExtra("info"));
        request = new ApplyStoreRequest();
        if (info != null) {
            try {
                request.setProduct_id(info.getProductId() + "");
                getDataForWeb(info.getProductId() + "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        request.setSales_type("1");
        request.setIs_imported("-1");
        request.setIs_muslim("-1");

        tvStoreWay.setText("包装");
        tvStoreOut.setText("否");
        tvStoreQz.setText("否");
        request.setStore_id(getIntent().getStringExtra("store"));

        imgList.add(null);

        rvStoreImg.setNestedScrollingEnabled(false);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvStoreImg.setLayoutManager(layoutManager);
        adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_apply_img) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                SquareImageView view = (SquareImageView) helper.getView(R.id.iv_item_apply_img);
                if (null != item) {
                    Glide.with(ApplyStoreActivity.this).load(item).override(AppConstant.SCREEN_WIDTH / 4, AppConstant.SCREEN_WIDTH / 4).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).into(view);
                }
            }
        };
        adapterImg.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == imgList.size() - 1) {
                    getImgInfo();
                }
            }
        });
        adapterImg.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                if (position != imgList.size() - 1) {
                    imgList.remove(position);
                    if (null != imgList.get(imgList.size() - 1)) {
                        imgList.add(null);
                        adapter.notifyDataSetChanged();
                    } else {
                        adapterImg.notifyItemRemoved(position);
                    }
                }
                return false;
            }
        });
        rvStoreImg.setItemAnimator(new DefaultItemAnimator());
        adapterImg.setNewData(imgList);
        rvStoreImg.setAdapter(adapterImg);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_apply_store;
    }

    @OnClick({R.id.tv_store_way, R.id.tv_store_out, R.id.tv_store_qz, R.id.btn_apply_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_store_way:
            case R.id.tv_store_out:
            case R.id.tv_store_qz:
                showTagDialog(view);
                break;
            case R.id.btn_apply_info:
                applyInfo();
                break;
        }
    }

    private void getImgInfo() {
        Picker.from(this).count(9 - imgList.size() + 1).enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_IMG);
    }

    private void showTagDialog(View view) {
        SelectPickerDialog<String> dialog = new SelectPickerDialog<>();
        dialog.setListener(new SelectPickerDialog.OnPickedListener<String>() {
            @Override
            public void onPickCompleted(String dataDesc) {
                switch (view.getId()) {
                    case R.id.tv_store_way:
                        request.setSales_type("包装".equals(dataDesc) ? "1" : "-1");
                        tvStoreWay.setText(dataDesc);
                        break;
                    case R.id.tv_store_out:
                        request.setIs_imported("是".equals(dataDesc) ? "1" : "-1");
                        tvStoreOut.setText(dataDesc);
                        break;
                    case R.id.tv_store_qz:
                        request.setIs_muslim("是".equals(dataDesc) ? "1" : "-1");
                        tvStoreQz.setText(dataDesc);
                        break;
                }
            }
        });
        dialog.show(getSupportFragmentManager());
        Subscription subscribe = rx.Observable.timer(100, TimeUnit.MILLISECONDS).compose(RxSchedulerUtils.normalSchedulersTransformer()).subscribe(new HttpSubscriber<Long>(this) {
            @Override
            public void onNext(Long aLong) {
                listTag.clear();
                switch (view.getId()) {
                    case R.id.tv_store_way:
                        listTag.add("包装");
                        listTag.add("散装");
                        break;
                    case R.id.tv_store_out:
                    case R.id.tv_store_qz:
                        listTag.add("是");
                        listTag.add("否");
                        break;
                }
                dialog.setDateList(listTag);
            }
        });
        subscription.add(subscribe);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMG && resultCode == Activity.RESULT_OK) {
            List<Uri> imgList = data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
            for (int i = 0; i < imgList.size(); i++) {
                this.imgList.add(0, FileUtils.getRealPathFromUri(this, imgList.get(i)));
            }
            if (this.imgList.size() >= 10) {
                this.imgList.remove(this.imgList.size() - 1);
            }
            adapterImg.setNewData(this.imgList);
        }
    }

    private void applyInfo() {
        request.setTitle(etStoreName.getText().toString());
        request.setBrand(etStoreBrand.getText().toString());
        request.setCode(etStoreBarcodes.getText().toString());
        request.setGuidance_price(etStorePrice.getText().toString());
        request.setLicence(etStoreCode.getText().toString());
        request.setShelf_life(etStoreDate.getText().toString());
        request.setStandard_number(etStoreNumber.getText().toString());
        request.setImgList(imgList);
        if (!checkParams()) {
            return;
        }
        rx.Observable<HttpResultEntity> storeInfo;
        if (info == null) {
            storeInfo = DataCenter.applyStoreInfo(request);
        } else {
            storeInfo = DataCenter.updateStoreInfo(request);
        }
        Subscription subscribe = storeInfo.subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading("发布中")) {
            @Override
            public void onNext(HttpResultEntity entity) {
                showToast(entity.getMessage());
                setResult(RESULT_OK);
                ApplyStoreActivity.this.finish();
            }
        });
        subscription.add(subscribe);
    }

    private boolean checkParams() {
        if (TextUtils.isEmpty(request.getTitle())) {
            showToast("请输入商品名称");
            return false;
        } else if (TextUtils.isEmpty(request.getGuidance_price())) {
            showToast("请输入商品指导价");
            return false;
        } else if (TextUtils.isEmpty(request.getLicence())) {
            showToast("请输入生产许可证编码");
            return false;
        } else {
            return true;
        }
    }


    private void getDataForWeb(String info) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("productId", info);
        Subscription subscribe = DataCenter.storeDetailInfo(map).subscribe(new HttpSubscriber<StoreDetailEntity>(this, showLoading()) {
            @Override
            public void onNext(StoreDetailEntity entity) {
                StoreDetailEntity.DataBean data = entity.getData();
                request.setSales_type("包装".equals(data.getSales_type()) ? "1" : "-1");
                request.setIs_imported("是".equals(data.getIs_imported()) ? "1" : "-1");
                request.setIs_muslim("是".equals(data.getIs_muslim()) ? "1" : "-1");
                request.setProduct_id(info);

                tvStoreWay.setText(data.getSales_type());
                tvStoreOut.setText(data.getIs_imported());
                tvStoreQz.setText(data.getIs_muslim());

                etStoreName.setText(data.getTitle());
                etStoreBrand.setText(data.getBrand());
                etStoreBarcodes.setText(data.getCode());
                etStorePrice.setText(data.getGuidance_price());
                etStoreCode.setText(data.getLicence());
                etStoreDate.setText(data.getShelf_life());
                etStoreNumber.setText(data.getStandard_number());

                imgList.addAll(0, data.getImg());
                adapterImg.setNewData(imgList);
            }
        });
        subscription.add(subscribe);
    }
}
